import 'dart:convert';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_search_bar_widget/common_search_bar_widget.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/test_function/bean/test_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/test_function/refresh_test_terminal_detail_page_event.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'bean/test_record_bean.dart';
import 'bean/test_un_qualified_count_response_bean.dart';
import 'bean/test_upload_bean.dart';

class TestFunctionViewModel extends BasePagerViewModel<TestItemBean, TestRecordBean>{

  static const String BIND_HSN_AND_ID_API = ServerApi.BASE_URL + "app/appBindSideNumber";
  static const String CHECK_HSN_API = ServerApi.BASE_URL + "app/appCheckHsn";
  static const String CHECK_ID_API = ServerApi.BASE_URL + "app/appCheckSideNumber";
  static const String TEST_DETAIL_API = ServerApi.BASE_URL + "app/appOutFactoryDetails";
  static const String UN_QUALIFIED_COUNT_API = ServerApi.BASE_URL + "app/appUnqualifiedCnt";
  static const String UPDATE_EACH_ITEM_CHECK_INFO_API = ServerApi.BASE_URL + "app/appUpdateEachItemCheckInfo";
  static const String UPDATE_ID_API = ServerApi.BASE_URL + "app/appUpdateSideNumber";
  static const String BIND_SIM_CARD_API = ServerApi.BASE_URL + "app/bindSIMCard";
  static const String BIND_SIM_CARD_NEW_API = ServerApi.BASE_URL + "app/bindSIMCardByICCID";

  ValueNotifier<int> totalValueNotifier;
  ValueNotifier<TestDetailAndCardInfoBean> testDetailValueNotifier;
  ValueNotifier<PlaceHolderStatusType> statusTypeValueNotifier;
  final CommonSearchGetContentCallback searchStrFunc;
  TestFunctionViewModel(BaseState<StatefulWidget> state, {this.searchStrFunc}) : super(state){
    totalValueNotifier = ValueNotifier(0);
    testDetailValueNotifier = ValueNotifier(null);
    statusTypeValueNotifier = ValueNotifier(PlaceHolderStatusType.loading);
  }



  ///出厂检测-标记机身编号
  void bindHsnAndId(BuildContext context,String hsn, String id, VoidCallback callback){
    if(StringUtils.isEmpty(hsn)){
      return;
    }
    VgHudUtils.show(context,"关联中");
    VgHttpUtils.get(BIND_HSN_AND_ID_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn":hsn,
      "sideNumber": id??"",
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, "关联成功");
          callback.call();
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }
    ));
  }

  ///出厂检测-hsn检测
  void checkHsn(BuildContext context, String hsn, {Function(bool success, String msg) callback}){
    if(StringUtils.isEmpty(hsn)){
      return;
    }
    VgHudUtils.show(context,);
    VgHttpUtils.get(CHECK_HSN_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn": hsn,
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          if(callback != null){
            callback.call(true, "");
          }
        },
        onError: (msg){
          VgHudUtils.hide(context);
          if("该显示屏已绑定机身编码" == msg){
            if(callback != null){
              callback.call(true, msg);
            }
          }else{
            VgToastUtils.toast(context, msg);
            if(callback != null){
              callback.call(false, "");
            }
          }
        }
    ));
  }


  ///出厂检测-侧身编号检测
  void checkId(BuildContext context, String id,{Function(bool success) callback}){
    if(StringUtils.isEmpty(id)){
      return;
    }
    VgHudUtils.show(context,);
    VgHttpUtils.get(CHECK_ID_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "sideNumber": id,
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          if(callback != null){
            callback.call(true);
          }
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
          if(callback != null){
            callback.call(false);
          }
        }
    ));
  }

  ///出厂检测-测试详情
  void getTestDetail(BuildContext context, String hsn){
    if(StringUtils.isEmpty(hsn)){
      return;
    }
    VgHttpUtils.get(TEST_DETAIL_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn": hsn,
    },callback: BaseCallback(
        onSuccess: (val){
          TestDetailResponseBean bean = TestDetailResponseBean.fromMap(val);
          if(!isStateDisposed){
            statusTypeValueNotifier?.value = null;
            testDetailValueNotifier?.value = bean?.data;
          }
        },
        onError: (msg){
          VgToastUtils.toast(context, msg);
          statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
        }
    ));
  }

  ///出厂检测-获取不合格数
  void getUnqualifiedCount(BuildContext context, Function(int count) callback){
    VgHudUtils.show(context,);
    VgHttpUtils.get(UN_QUALIFIED_COUNT_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          TestUnQualifiedCountResponseBean bean = TestUnQualifiedCountResponseBean.fromMap(val);
          callback.call(bean.data);
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }
    ));
  }

  ///出厂检测-各项检测信息修改
  void updateId(BuildContext context, String hsn, String id, {VoidCallback callback}){
    TestUploadBean testUploadBean = TestUploadBean(hsn: hsn, sideNumber: id);
    VgHudUtils.show(context,"获取中");
    print("testUploadBean:" + json.encode(testUploadBean).toString());
    VgHttpUtils.post(UPDATE_ID_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn": hsn,
      "sideNumber": id,
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          if(callback != null){
            callback.call();
          }else{
            getTestDetail(context, hsn);
          }
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }
    ));
  }

  ///出厂检测-各项检测信息修改
  void testFuctionItem(BuildContext context, TestUploadBean uploadBean){
    VgHudUtils.show(context,"获取中");
    VgHttpUtils.get(UPDATE_EACH_ITEM_CHECK_INFO_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "sysTestItem": json.encode(uploadBean)
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }
    ));
  }

  ///绑定sim卡
  ///reBind 00默认 01确定重绑
  void bindSimCard(BuildContext context, String hsn, String ICCID, String reBind){
    if(StringUtils.isEmpty(hsn)){
      return;
    }
    VgHudUtils.show(context,"请稍候");
    VgHttpUtils.post(BIND_SIM_CARD_NEW_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn":hsn,
      "ICCID": ICCID??"",
      "reBind": reBind??"00",
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, "设置成功");
          VgEventBus.global.send(new RefreshTestTerminalDetailPageEvent());
        },
        onError: (msg)async{
          VgHudUtils.hide(context);
          if(msg.contains("该4G卡已绑定以下设备")){
            RouterUtils.pop(context);
            bool result =
                await CommonConfirmCancelDialog.navigatorPushDialog(context,
                title: "提示",
                content: msg,
                cancelText: "取消",
                confirmText: "确定",
                confirmBgColor: ThemeRepository.getInstance()
                    .getPrimaryColor_1890FF());
            if(result??false){
              bindSimCard(context, hsn, ICCID, "01");
            }
          }else{
            VgToastUtils.toast(context, msg);
          }
        }
    ));
  }


  @override
  void onDisposed() {
    if(!isStateDisposed){
      totalValueNotifier?.dispose();
      testDetailValueNotifier?.dispose();
      statusTypeValueNotifier?.dispose();
    }
    super.onDisposed();
  }


  @override
  String getBodyData(int page) {
    return null;
  }

  @override
  Map<String, dynamic> getQuery(int page) {
    Map<String, dynamic> map = {
      "authId": UserRepository.getInstance().authId ?? "",
      "current": page ?? 1,
      "size": 20,
      if(StringUtils.isNotEmpty(searchStrFunc?.call() ?? ""))
        "keyword":searchStrFunc?.call() ?? "",
    };
    return map;
  }

  @override
  String getRequestMethod() {
    return HttpUtils.GET;
  }

  @override
  String getUrl() {
    return ServerApi.BASE_URL + "app/appOutFactoryRecord";
  }
  @override
  bool isNeedCache() {
    return true;
  }

  @override
  String getCacheKey() {
    return getUrl() + (UserRepository.getInstance().companyId??"");
  }

  @override
  TestRecordBean parseData(VgHttpResponse resp) {
    TestRecordBean vo = TestRecordBean.fromMap(resp?.data);
    loading(false);
    totalValueNotifier?.value = vo?.data?.page?.total ?? 0;
    return vo;
  }

}